import axios from 'axios'

import $router from '@/common/router/router'
import $store from "@/common/store/_store";
import {message, Modal} from "ant-design-vue";
import {createVNode,} from 'vue';
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";

const $http = axios.create({timeout: 100 * 1000});

// 请求拦截  设置统一header
$http.interceptors.request.use(config => {
    let url = config.url;
    let haveHttp = (url + "").indexOf("http://").toString() !== "-1";
    let haveHttps = (url + "").indexOf("https://").toString() !== "-1";
    if (haveHttp || haveHttps) {
    } else {
        config.url = import.meta.env.VITE_SERVER_URL + url;
        config.headers['Token'] = localStorage.getItem("Token");
    }
    ////console.log(config)
    return config;
}, error => {
    // ////////////console.log("http-" + 16)
    return Promise.reject(error)
});

$http.interceptors.response.use(async response => {
    //////console.log("http-" + 20)
    ////console.log(response)

    //TODO Token失效，自动刷新Token
    if (response.data.code == 409) {
        //登录超时操作
        Modal.confirm({
            title: '登录超时',
            icon: createVNode(ExclamationCircleOutlined),
            content: '登录已超时，点击 “退出” 退出系统，点击 “刷新” 尝试重新登录',
            okText: "刷新",
            cancelText: "退出",
            async onOk() {
                await $http.post(
                    '/system/user/refreshToken',
                    {
                        userId: localStorage.getItem("userId"),
                        refreshToken: localStorage.getItem("refreshToken")
                    }
                ).then((res) => {
                    if (res.status) {
                        localStorage.setItem("Token", res.data.token)
                        localStorage.setItem("refreshToken", res.data.refreshToken)
                        message.success("登录成功，欢迎继续使用。")
                        let route = $router.currentRoute.value
                        //console.log("route", route)
                        $router.push(route.path)
                    } else {
                        localStorage.removeItem("Token")
                        localStorage.removeItem("refreshToken")

                        //退出登录
                        $store.state.includeRouter = [];
                        $router.push("/public/login")
                    }
                    return null;
                })
            },
            onCancel() {
                ////console.log(res.message)
                localStorage.removeItem("Token")
                localStorage.removeItem("refreshToken")
                //退出登录
                $store.state.includeRouter = [];
                $router.push("/public/login")
            },
        });

        $store.state.windowLoading = false
        $store.state.pageLoading = false
        return null;
    }

    return response.data;
}, error => {
    $store.state.windowLoading = false
    $store.state.pageLoading = false
    // ////////////console.log("http-" + 24)
    if (error.message === "Network Error") {
        $router.push(`/public/serverStop`)
    }
    // if (error.message.indexOf("404") != -1) {
    //     alert("请求地址不存在，404")
    // }
    if (error.response.status == 404) {
        message.warning(`请求地址【${error.request.responseURL}】不存在`)
    }
    //////console.log("error.message", error.message)
    // ////////////console.log("error.request", error.request)
    // ////////////console.log("error.response", error.response)

    return Promise.reject({message: error.message, request: error.request, response: error.response})
});

export default $http

